using UnityEngine;
using System.Collections.Generic;

/// <summary>
/// UI复用列表Item对象池
/// </summary>
public class UIReuseItemPool
{
    Dictionary<System.Type, Stack<UIReuseItem>> pools = new();

    public UIReuseItemPool()
    {
    }

    public UIReuseItem New(UIReuseItem template, Transform hierarchyParent)
    {
        var type = template.GetType();
        if (!pools.TryGetValue(type, out var pool))
        {
            pool = new Stack<UIReuseItem>();
            pools[type] = pool;
        }

        if (pool.Count > 0)
            return pool.Pop();
        else
        {
            var item = Object.Instantiate(template, hierarchyParent, false);
            item.name = item.name.Replace("(Clone)", "");
            item.gameObject.SetActive(false);
            return item;
        }
    }

    public void Recycle(UIReuseItem view)
    {
        if (view != null)
        {
            var type = view.GetType();
            if (pools.TryGetValue(type, out var pool))
                pool.Push(view);
        }
    }

    public void ReleaseAll()
    {
        foreach (var pool in pools.Values)
        {
            foreach (var item in pool)
                if (item.gameObject) Object.Destroy(item.gameObject);
            pool.Clear();
        }
        pools.Clear();
    }
}

